package service

import (
	"errors"
	"fmt"
	"github.com/go-admin-team/go-admin-core/sdk/service"
	"gorm.io/gorm"
	"net"
	"strconv"
	"strings"
	"time"
	"vrcm/src/vrcm/app/admin/models/domian"
	ccEngineService "vrcm/src/vrcm/app/admin/service/ccengine"
	ccenginDto "vrcm/src/vrcm/app/admin/service/dto/ccengine"
	"vrcm/src/vrcm/app/admin/service/dto/domian"
	"vrcm/src/vrcm/common/apis"
	cDto "vrcm/src/vrcm/common/dto"
)

type DomainConfig struct {
	service.Service
}

var serviceTypeMap = map[int]string{
	1: "web",
	2: "download",
	3: "media",
	4: "hybrid",
	5: "dynamic",
}

var areaMap = map[int]string{
	1: "mainland",
	2: "overseas",
	3: "global",
}

var redirectTypeMap = map[int]string{
	1: "https",
	2: "http",
}

var cacheTypeMap = map[int]string{
	1: "directory",
	2: "file",
	3: "path",
	4: "all",
}

var filterTypeMap = map[int]string{
	1: "includeAll",
	2: "excludeAll",
	3: "includeCustom",
	4: "excludeCustom",
}

// s-秒 m-分 h-小时 d-天
var unitMap = map[int]string{
	1: "s",
	2: "m",
	3: "h",
	4: "d",
}

// GetPage 获取DomainConfig列表
func (e *DomainConfig) GetPage(c *dto.DomainConfigGetPageReq, count *int64) ([]domain.DomainConfigModel, error) {
	var err error
	var configs []domain.DomainConfig
	data := make([]domain.DomainConfigModel, 0, 5)
	err = e.Orm.Model(&domain.DomainConfig{}).
		Scopes(
			cDto.MakeCondition(c.GetNeedSearch()),
			cDto.Paginate(c.GetPageSize(), c.GetPageIndex()),
		).
		Find(&configs).Limit(-1).Offset(-1).
		Count(count).Error
	if err != nil {
		e.Log.Errorf("DomainConfigService GetPage error:%s \r\n", err)
		return nil, err
	}

	ids := make([]int, 0, 5)
	domainMap := make(map[int]domain.DomainConfig)
	for _, v := range configs {
		v := v
		domainMap[v.Id] = v
		ids = append(ids, v.Id)
	}

	sourceStationMap := make(map[int][]domain.SourceStationConfig)
	sourceStations := make([]domain.SourceStationConfig, 0, 5)
	err = e.Orm.Model(domain.SourceStationConfig{}).Where("domain_id in ?", ids).Find(&sourceStations).Error
	if err != nil {
		e.Log.Errorf("get SourceStationConfig error:%s \r\n", err)
		return nil, err
	}

	for _, v := range sourceStations {
		v := v
		sourceStation, ok := sourceStationMap[v.DomainId]
		if !ok {
			sourceStation = make([]domain.SourceStationConfig, 0, 5)
		}
		sourceStation = append(sourceStation, v)
		sourceStationMap[v.DomainId] = sourceStation
	}

	backSourceConfigMap := make(map[int]domain.BackSourceConfig)
	backSourceConfigs := make([]domain.BackSourceConfig, 0, 5)
	err = e.Orm.Model(domain.BackSourceConfig{}).Where("domain_id in ?", ids).Find(&backSourceConfigs).Error
	if err != nil {
		e.Log.Errorf("Get BackSourceConfig error:%s \r\n", err)
		return nil, err
	}
	for _, v := range backSourceConfigs {
		v := v
		backSourceConfigMap[v.DomainId] = v
	}

	cacheExpireMap := make(map[int][]domain.CacheExpireConfig)
	cacheExpireConfigs := make([]domain.CacheExpireConfig, 0, 5)
	err = e.Orm.Model(domain.CacheExpireConfig{}).Where("domain_id in ?", ids).Find(&cacheExpireConfigs).Error
	if err != nil {
		e.Log.Errorf("Get CacheExpireConfig error:%s \r\n", err)
		return nil, err
	}
	for _, v := range cacheExpireConfigs {
		v := v
		cacheExpire, ok := cacheExpireMap[v.DomainId]
		if !ok {
			cacheExpire = make([]domain.CacheExpireConfig, 0, 5)
		}
		cacheExpire = append(cacheExpire, v)
		cacheExpireMap[v.DomainId] = cacheExpire
	}

	cacheFilterMap := make(map[int][]domain.CacheFilterConfig)
	cacheFilterConfigs := make([]domain.CacheFilterConfig, 0, 5)
	err = e.Orm.Model(domain.CacheFilterConfig{}).Where("domain_id in ?", ids).Find(&cacheFilterConfigs).Error
	if err != nil {
		e.Log.Errorf("Get CacheFilterConfig error:%s \r\n", err)
		return nil, err
	}
	for _, v := range cacheFilterConfigs {
		v := v
		cacheFilter, ok := cacheFilterMap[v.DomainId]
		if !ok {
			cacheFilter = make([]domain.CacheFilterConfig, 0, 5)
		}
		cacheFilter = append(cacheFilter, v)
		cacheFilterMap[v.DomainId] = cacheFilter
	}

	distributionProtocolMap := make(map[int]domain.DistributionProtocol)
	distributionProtocols := make([]domain.DistributionProtocol, 0, 5)
	err = e.Orm.Model(domain.DistributionProtocol{}).Where("domain_id in ?", ids).Find(&distributionProtocols).Error
	if err != nil {
		e.Log.Errorf("Get DistributionProtocol error:%s \r\n", err)
		return nil, err
	}
	for _, v := range distributionProtocols {
		v := v
		distributionProtocolMap[v.DomainId] = v
	}

	for _, v := range configs {
		v := v
		model := domain.DomainConfigModel{}
		model.DomainConfig = v
		sourceStationConfigs := sourceStationMap[v.Id]
		model.SourceStationConfigs = sourceStationConfigs
		cacheExpires := cacheExpireMap[v.Id]
		model.CacheExpireConfigs = cacheExpires
		cacheFilters := cacheFilterMap[v.Id]
		model.CacheFilterConfigs = cacheFilters
		distributionProtocol := distributionProtocolMap[v.Id]
		model.DistributionProtocol = distributionProtocol
		backSourceConfig := backSourceConfigMap[v.Id]
		model.BackSourceConfig = backSourceConfig
		data = append(data, model)
	}
	return data, nil
}

// Get 获取DomainConfig对象
func (e *DomainConfig) Get(d *dto.DomainConfigGetReq, tx *gorm.DB) (*domain.DomainConfigModel, error) {
	var data domain.DomainConfigModel

	var domainConfig domain.DomainConfig
	err := tx.Model(domain.DomainConfig{}).Where("id=?", d.Id).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get DomainConfig error:%s \r\n", err)
		return nil, err
	}
	data.DomainConfig = domainConfig
	sourceStations := make([]domain.SourceStationConfig, 0, 5)
	err = tx.Model(domain.SourceStationConfig{}).Where("domain_id=?", domainConfig.Id).Find(&sourceStations).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get SourceStationConfig error:%s \r\n", err)
		return nil, err
	}
	if len(sourceStations) > 0 {
		data.SourceStationConfigs = sourceStations
	} else {
		data.SourceStationConfigs = nil
	}

	var backSourceConfig domain.BackSourceConfig
	err = tx.Model(domain.BackSourceConfig{}).Where("domain_id=?", d.Id).Find(&backSourceConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get BackSourceConfig error:%s \r\n", err)
		return nil, err
	}

	if backSourceConfig.Id > 0 {
		data.BackSourceConfig = backSourceConfig
	}
	//else {
	//	data.BackSourceConfig = nil
	//}

	cacheExpireConfigs := make([]domain.CacheExpireConfig, 0, 5)
	err = tx.Model(domain.CacheExpireConfig{}).Order("sort asc").Where("domain_id=?", d.Id).Find(&cacheExpireConfigs).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get CacheExpireConfig error:%s \r\n", err)
		return nil, err
	}
	//for k, _ := range cacheExpireConfigs {
	//	*(&cacheExpireConfigs[k].Priority) = 100 - k
	//}

	if len(cacheExpireConfigs) > 0 {
		data.CacheExpireConfigs = cacheExpireConfigs
	}

	stateCodeExpireConfigs := make([]domain.StateCodeExpireConfig, 0, 5)
	err = tx.Model(domain.StateCodeExpireConfig{}).Where("domain_id=?", d.Id).Find(&stateCodeExpireConfigs).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get StateCodeExpireConfig error:%s \r\n", err)
		return nil, err
	}
	if len(stateCodeExpireConfigs) > 0 {
		data.StateCodeExpireConfigs = stateCodeExpireConfigs
	}

	//else {
	//	data.StateCodeExpireConfigs = nil
	//}

	cacheFilterConfigs := make([]domain.CacheFilterConfig, 0, 5)
	err = tx.Model(domain.CacheFilterConfig{}).Order("sort asc").Where("domain_id=?", d.Id).Find(&cacheFilterConfigs).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get cacheFilterConfig error:%s \r\n", err)
		return nil, err
	}
	if len(cacheFilterConfigs) > 0 {
		data.CacheFilterConfigs = cacheFilterConfigs
	}

	//for k, _ := range cacheFilterConfigs {
	//	*(&cacheFilterConfigs[k].Priority) = 100 - k
	//}
	//else {
	//	data.CacheFilterConfigs = nil
	//}

	var distributionProtocol domain.DistributionProtocol
	err = tx.Model(domain.DistributionProtocol{}).Where("domain_id=?", d.Id).Find(&distributionProtocol).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get distributionProtocol error:%s \r\n", err)
		return nil, err
	}
	if distributionProtocol.Id > 0 {
		data.DistributionProtocol = distributionProtocol
	}

	//else {
	//	data.DistributionProtocol = nil
	//}

	//获取证书
	var certificate domain.Certificate
	err = tx.Model(domain.Certificate{}).Where("id=?", domainConfig.CertificateId).Find(&certificate).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get Certificate error:%s \r\n", err)
		return nil, err
	}
	if certificate.Id > 0 {
		data.Certificate = certificate
	}

	//else {
	//	data.Certificate = nil
	//}

	//防盗链
	var antiTheftConfig domain.AntiTheftConfig
	err = tx.Model(domain.AntiTheftConfig{}).Where("domain_id=?", d.Id).Find(&antiTheftConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get AntiTheftConfig error:%s \r\n", err)
		return nil, err
	}
	if antiTheftConfig.Id > 0 {
		data.AntiTheftConfig = antiTheftConfig
	}

	//else {
	//	data.AntiTheftConfig = nil
	//}
	overWriteUrls := make([]domain.OverWriteUrl, 0, 4)
	err = tx.Model(&domain.OverWriteUrl{}).Order("sort asc").Where("domain_id = ?", d.Id).Find(&overWriteUrls).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get OverWriteUrl error:%s \r\n", err)
		return nil, err
	}
	data.OverWriteUrls = overWriteUrls
	var urlSign domain.UrlSign
	err = tx.Model(domain.UrlSign{}).Where("domain_id=?", d.Id).Find(&urlSign).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get UrlSign error:%s \r\n", err)
		return nil, err
	}
	data.UrlSign = urlSign

	requestHeaders := make([]domain.HeaderConfig, 0, 4)
	err = tx.Model(domain.HeaderConfig{}).Where("domain_id=? and header_type=1", d.Id).Find(&requestHeaders).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get requestHeader error:%s \r\n", err)
		return nil, err
	}
	data.RequestHeaderConfigs = requestHeaders

	responseHeaders := make([]domain.HeaderConfig, 0, 4)
	err = tx.Model(domain.HeaderConfig{}).Where("domain_id=? and header_type=2", d.Id).Find(&responseHeaders).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get responseHeaders error:%s \r\n", err)
		return nil, err
	}
	data.ResponseHeaderConfigs = responseHeaders

	//防盗链
	var compressConfig domain.CompressConfig
	err = tx.Model(domain.CompressConfig{}).Where("domain_id=?", d.Id).Find(&compressConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Get CompressConfig error:%s \r\n", err)
		return nil, err
	}
	if compressConfig.Id > 0 {
		data.CompressConfig = compressConfig
	}

	return &data, nil
}

// Insert 创建DomainConfig对象
func (e *DomainConfig) Insert(c *dto.DomainConfigInsertReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	var err error
	var data domain.DomainConfig
	c.Generate(&data)
	err = tx.Create(&data).Error
	if err != nil {
		e.Log.Errorf("DomainConfigService Insert error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	now := time.Now().Unix()
	for k, v := range c.SourceStationAddresses {
		if v.Priority <= 0 || v.Priority > 2 {
			//e.Log.Errorf("DomainConfigService Insert error:%s \r\n", err)
			tx.Rollback()
			return errors.New(string(apis.ParamterValidatorError.Code))
		}
		*(&c.SourceStationAddresses[k].CreateTime) = now
		*(&c.SourceStationAddresses[k].UpdateTime) = now
		*(&c.SourceStationAddresses[k].DomainId) = data.Id
		*(&c.SourceStationAddresses[k].TenantId) = c.TenantId
	}
	if len(c.SourceStationAddresses) > 0 {
		err = tx.Model(domain.SourceStationConfig{}).Create(&c.SourceStationAddresses).Error
		if err != nil {
			e.Log.Errorf("Insert SourceStationConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	c.BackSourceConfig.CreateTime = now
	c.BackSourceConfig.UpdateTime = now
	c.BackSourceConfig.DomainId = data.Id
	c.BackSourceConfig.TenantId = c.TenantId
	err = tx.Model(domain.BackSourceConfig{}).Create(&c.BackSourceConfig).Error
	if err != nil {
		e.Log.Errorf("Insert BackSourceConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	c.Id = data.Id

	expire := domain.CacheExpireConfig{}
	expire.Id = 0
	expire.ExpireType = 4
	expire.DomainId = data.Id
	expire.TenantId = c.TenantId
	expire.Unit = 4
	//1秒 2分 3时 4天 5月 6年
	expire.ExpireTime = 30
	expire.CacheSet = 1
	expire.Content = ""
	expire.Sort = 0
	err = tx.Save(&expire).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save CacheExpireConfig error:%s \r\n", err)
		return err
	}

	filter := domain.CacheFilterConfig{}
	filter.Id = 0
	filter.ExpireType = 4
	filter.IgnoreFilter = 1
	//expire.ExpireTime = c.ExpireTime
	filter.DomainId = data.Id
	filter.TenantId = c.TenantId
	filter.Sort = 0
	filter.FilterParam = ""
	//expire.Unit = c.Unit
	//1秒 2分 3时 4天 5月 6年
	//filter.ExpireTime = 60 * 60 * 24 * 30
	//filter.CacheSet = c.CacheSet
	filter.Content = ""
	err = tx.Save(&filter).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save CacheFilterConfig error:%s \r\n", err)
		return err
	}

	//创建域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: data.Id}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		res, err := ccEngineService.CreateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		param := make(map[string]interface{})
		if res != nil {
			param["cname"] = res.Cname
			param["domain_task_id"] = res.Id
			param["domain_state"] = 2
			param["zone_id"] = res.ZoneId
			param["update_time"] = now
			err = tx.Model(&domain.DomainConfig{}).Where("id=?", data.Id).Updates(&param).Error
			if err != nil {
				e.Log.Errorf("UpdateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}
	tx.Commit()

	return nil
}

// Update 修改DomainConfig对象
func (e *DomainConfig) Update(c *dto.DomainConfigUpdateReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	now := time.Now().Unix()
	param := make(map[string]interface{})
	param["ac_area"] = c.AcArea
	param["range"] = c.Range
	param["range"] = c.Range
	param["update_time"] = now
	err := tx.Model(&domain.DomainConfig{}).Where("id=?", c.Id).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("UpdateDomain error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	for _, config := range *c.SourceStationAddresses {
		if config.Priority <= 0 || config.Priority > 2 {
			//e.Log.Errorf("DomainConfigService Insert error:%s \r\n", err)
			tx.Rollback()
			return errors.New(string(apis.ParamterValidatorError.Code))
		}
	}

	if c.BackSourceConfig.Id > 0 {
		param1 := make(map[string]interface{})
		param1["protocol"] = c.BackSourceConfig.Protocol
		param1["host"] = c.BackSourceConfig.Host
		param1["ipv6_accelerate"] = c.BackSourceConfig.Ipv6Accelerate
		param1["origin_timeout"] = c.BackSourceConfig.OriginTimeout
		param1["update_time"] = now
		err = tx.Model(&domain.BackSourceConfig{}).Where("domain_id=?", c.BackSourceConfig.DomainId).Updates(&param1).Error
		if err != nil {
			e.Log.Errorf("update BackSourceConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	if c.SourceStationAddresses != nil {
		err = tx.Model(&domain.SourceStationConfig{}).Where("domain_id=?", c.Id).Delete(&domain.SourceStationConfig{}).Error
		if err != nil {
			e.Log.Errorf("delete SourceStationConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		err = tx.Model(&domain.SourceStationConfig{}).Save(&c.SourceStationAddresses).Error
		if err != nil {
			e.Log.Errorf("save SourceStationConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: c.Id}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err := ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	tx.Commit()
	return nil
}

func (e *DomainConfig) UpdateDomain(c *dto.DomainConfigUpdateReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	now := time.Now().Unix()
	param := make(map[string]interface{})
	param["ac_area"] = c.AcArea
	param["range"] = c.Range
	param["range"] = c.Range
	param["update_time"] = now
	err := tx.Model(&domain.DomainConfig{}).Where("id=?", c.Id).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("UpdateDomain error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	if c.BackSourceConfig != nil {
		if c.BackSourceConfig.OriginTimeout < 5 || c.BackSourceConfig.OriginTimeout > 60 {
			return errors.New(string(apis.OriginTimeOutError.Code))
		}
		param1 := make(map[string]interface{})
		param1["protocol"] = c.BackSourceConfig.Protocol
		param1["host"] = c.BackSourceConfig.Host
		param1["ipv6_accelerate"] = c.BackSourceConfig.Ipv6Accelerate
		param1["origin_timeout"] = c.BackSourceConfig.OriginTimeout
		param1["enable_trace"] = c.BackSourceConfig.EnableTrace
		param1["update_time"] = now
		err = tx.Model(&domain.BackSourceConfig{}).Where("domain_id=?", c.BackSourceConfig.DomainId).Updates(&param1).Error
		if err != nil {
			e.Log.Errorf("update BackSourceConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	for _, config := range *c.SourceStationAddresses {
		if config.Priority <= 0 || config.Priority > 2 {
			//e.Log.Errorf("DomainConfigService Insert error:%s \r\n", err)
			tx.Rollback()
			return errors.New(string(apis.ParamterValidatorError.Code))
		}
	}

	if c.SourceStationAddresses != nil {
		err = tx.Model(&domain.SourceStationConfig{}).Where("domain_id=?", c.Id).Delete(&domain.SourceStationConfig{}).Error
		if err != nil {
			e.Log.Errorf("delete SourceStationConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		err = tx.Model(&domain.SourceStationConfig{}).Save(&c.SourceStationAddresses).Error
		if err != nil {
			e.Log.Errorf("save SourceStationConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	if c.UrlSign != nil {
		err = tx.Model(&domain.UrlSign{}).Where("domain_id=?", c.Id).Delete(&domain.UrlSign{}).Error
		if err != nil {
			e.Log.Errorf("delete UrlSign error:%s \r\n", err)
			tx.Rollback()
			return err
		}

		err = e.SaveUrlSign(tx, c.UrlSign, true)
		if err != nil {
			e.Log.Errorf("save UrlSign error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	if c.AntiTheftConfig != nil {
		err = tx.Model(&domain.AntiTheftConfig{}).Where("domain_id=?", c.Id).Delete(&domain.AntiTheftConfig{}).Error
		if err != nil {
			e.Log.Errorf("delete AntiTheftConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		err = e.SaveAntiTheftConfig(tx, c.AntiTheftConfig, true)
		if err != nil {
			e.Log.Errorf("save AntiTheftConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	if c.CacheExpireConfig != nil {
		err = e.SaveMultiCacheExpireConfig(tx, c.CacheExpireConfig, true)
		if err != nil {
			e.Log.Errorf("SaveMultiCacheExpireConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	if c.CacheFilterConfig != nil {
		err = e.SaveMultiCacheFilterConfig(tx, c.CacheFilterConfig, true)
		if err != nil {
			e.Log.Errorf("SaveMultiCacheFilterConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	if c.DistributionProtocol != nil {
		err = e.SaveDistributionProtocol(tx, c.DistributionProtocol, true)
		if err != nil {
			e.Log.Errorf("SaveDistributionProtocol error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	if c.StateCodeExpireConfig != nil {
		err = e.SaveMultiStateCodeExpireConfig(tx, c.StateCodeExpireConfig, true)
		if err != nil {
			e.Log.Errorf("SaveMultiStateCodeExpireConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	if c.HeaderConfigs != nil {
		err = e.SaveMultiHeaderConfig1(tx, c.HeaderConfigs, true)
		if err != nil {
			e.Log.Errorf("SaveMultiHeaderConfig1 error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	if c.CompressConfig != nil {
		fmt.Println("阿娇喝点酒啊活动阿迪克拉大肚腩。，andad", c.CompressConfig)

		err = e.SaveCompressConfig(tx, c.CompressConfig, true)
		if err != nil {
			e.Log.Errorf("SaveCompressConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	//e.SaveUrlSign(dto.UrlSignSaveReq{})

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: c.Id}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err = ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	tx.Commit()
	return nil
}

// Remove 删除DomainConfig
func (e *DomainConfig) Remove(d *dto.DomainConfigDeleteReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log

	data := make([]domain.DomainConfig, 0, 5)
	err := tx.Model(&domain.DomainConfig{}).Where("id in ?", d.Ids).Find(&data).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}

	isEnable := false
	for _, v := range data {
		if v.DomainState == 2 {
			isEnable = true
			break
		}
	}

	if isEnable {
		return errors.New("加速域名正在启用，无法删除！")
	}

	err = tx.Model(&domain.DomainConfig{}).Where("id in ?", d.Ids).Delete(&domain.DomainConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete DomainConfig error:%s \r\n", err)
		return err
	}

	err = tx.Model(&domain.SourceStationConfig{}).Where("domain_id in ?", d.Ids).Delete(&domain.SourceStationConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete SourceStationConfig error:%s \r\n", err)
		return err
	}

	err = tx.Model(&domain.BackSourceConfig{}).Where("domain_id in ?", d.Ids).Delete(&domain.BackSourceConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete BackSourceConfig error:%s \r\n", err)
		return err
	}

	err = tx.Model(&domain.CacheExpireConfig{}).Where("domain_id in ?", d.Ids).Delete(&domain.CacheExpireConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete CacheExpireConfig error:%s \r\n", err)
		return err
	}

	err = tx.Model(&domain.CacheFilterConfig{}).Where("domain_id in ?", d.Ids).Delete(&domain.CacheFilterConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete CacheFilterConfig error:%s \r\n", err)
		return err
	}

	err = tx.Model(&domain.DistributionProtocol{}).Where("domain_id in ?", d.Ids).Delete(&domain.DistributionProtocol{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete DistributionProtocol error:%s \r\n", err)
		return err
	}

	for _, v := range data {
		err = ccEngineService.DeleteDomain(&ccenginDto.DomainReq{Id: v.DomainTaskId, TenantId: v.TenantId})
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("DeleteDomain error:%s \r\n", err)
			return err
		}

	}

	tx.Commit()
	return nil
}

func (e *DomainConfig) SaveBackSourceConfig(c *dto.BackSourceConfigSaveReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	var domainConfig domain.DomainConfig
	err := e.Orm.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}
	param1 := make(map[string]interface{})
	param1["enable_trace"] = c.EnableTrace
	err = tx.Model(&domain.BackSourceConfig{}).Where("domain_id=?", c.DomainId).Updates(&param1).Error
	if err != nil {
		e.Log.Errorf("update BackSourceConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err := ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}

func (e *DomainConfig) SaveSourceStationConfig(c *dto.SourceStationConfigSaveReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	var domainConfig domain.DomainConfig
	err := e.Orm.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}

	station := domain.SourceStationConfig{}
	now := time.Now().Unix()
	station.Id = c.Id
	station.SourceStationIp = c.SourceStationIp
	station.Port = c.Port
	station.TenantId = c.TenantId
	station.DomainId = c.DomainId
	station.Weight = c.Weight
	station.Priority = c.Priority
	if c.Id > 0 {
		station.UpdateTime = time.Now().Unix()
	} else {
		station.CreateTime = now
		station.UpdateTime = now
	}
	err = e.Orm.Model(domain.SourceStationConfig{}).Save(&station).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save SourceStationConfig error:%s \r\n", err)
		return err
	}

	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err := ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}

	c.Id = station.Id
	tx.Commit()
	return nil
}

func (e *DomainConfig) DeleteSourceStationConfig(d *dto.SourceStationConfigDeleteReq) error {

	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	var data domain.SourceStationConfig

	db := tx.Model(&data).Delete(&data, d.Id)
	if err := db.Error; err != nil {
		tx.Rollback()
		e.Log.Errorf("DeleteSourceStationConfig error:%s \r\n", err)
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: d.DomainId}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err := ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	return nil
}

func (e *DomainConfig) SaveCacheExpireConfig(c *dto.CacheExpireConfigSaveReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}

	//获取最后一个记录
	var cacheConfig domain.CacheExpireConfig
	tx.Model(&domain.CacheExpireConfig{}).Order("sort desc").Where("domain_id = ?", c.DomainId).First(&cacheConfig)
	sort := cacheConfig.Sort
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}
	expire := domain.CacheExpireConfig{}
	now := time.Now().Unix()
	expire.Id = c.Id
	expire.ExpireType = c.ExpireType
	expire.ExpireTime = c.ExpireTime
	expire.DomainId = c.DomainId
	expire.TenantId = c.TenantId
	expire.Unit = c.Unit
	expire.CacheSet = c.CacheSet
	expire.Content = c.Content
	expire.Priority = c.Priority
	if c.Id > 0 {
		expire.Sort = c.Sort
		expire.UpdateTime = time.Now().Unix()
	} else {
		expire.Sort = sort + 1
		expire.CreateTime = now
		expire.UpdateTime = now
	}
	err = tx.Save(&expire).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save CacheExpireConfig error:%s \r\n", err)
		return err
	}

	configs := make([]domain.CacheExpireConfig, 0, 5)
	err = tx.Model(&domain.CacheExpireConfig{}).Where("domain_id=?", c.DomainId).Find(&configs).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get CacheExpireConfig error:%s \r\n", err)
		return err
	}

	config := &domain.CacheExpireConfig{}
	err = tx.Model(&domain.CacheExpireConfig{}).Where("expire_type=4 and domain_id=?", c.DomainId).Find(&config).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get CacheExpireConfig error:%s \r\n", err)
		return err
	}

	if config.Sort >= cacheConfig.Sort {
		err = tx.Model(&domain.CacheExpireConfig{}).Where("expire_type=4 and domain_id=?", c.DomainId).Update("sort", sort+2).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("Update CacheExpireConfig error:%s \r\n", err)
			return err
		}
	}

	//flag := false
	//for _, cache := range configs {
	//	if cache.ExpireType == 4 {
	//		flag = true
	//	}
	//}
	//if !flag {
	//	sort = sort + 1
	//	expire := domain.CacheExpireConfig{}
	//	expire.Id = 0
	//	expire.ExpireType = 4
	//	expire.DomainId = c.DomainId
	//	expire.TenantId = c.TenantId
	//	expire.Unit = 4
	//	//1秒 2分 3时 4天 5月 6年
	//	expire.ExpireTime = 30
	//	expire.CacheSet = 1
	//	expire.Content = ""
	//	expire.Sort = sort
	//	err = tx.Save(&expire).Error
	//	if err != nil {
	//		tx.Rollback()
	//		e.Log.Errorf("save CacheExpireConfig error:%s \r\n", err)
	//		return err
	//	}
	//}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err = ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	c.Id = expire.Id

	tx.Commit()
	return nil
}

func (e *DomainConfig) SaveMultiCacheExpireConfig(tx *gorm.DB, c *dto.MultiCacheExpireConfigSaveReq, isSkip bool) error {

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		tx.Rollback()
		return errors.New("加速域名不存在")
	}

	err = tx.Model(&domain.CacheExpireConfig{}).Where("domain_id=?", c.DomainId).Delete(&domain.CacheExpireConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete CacheExpireConfig error:%s \r\n", err)
		return err
	}

	tenantId := ""
	if len(c.Params) > 0 {
		tenantId = c.Params[0].TenantId
	}
	configs := make([]domain.CacheExpireConfig, 0, 5)
	err = tx.Model(&domain.CacheExpireConfig{}).Where("domain_id=?", c.DomainId).Find(&configs).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get CacheExpireConfig error:%s \r\n", err)
		return err
	}

	//获取最后一个记录
	var cacheConfig domain.CacheExpireConfig
	tx.Model(&domain.CacheExpireConfig{}).Where("domain_id=?", c.DomainId).Order("sort desc").First(&cacheConfig)
	sort := cacheConfig.Sort
	//判断有没有全部文件类型 没有添加
	flag := false

	for _, cache := range configs {
		cache := cache
		if cache.ExpireType == 4 {
			flag = true
		}
	}
	expire4 := domain.CacheExpireConfig{}
	if !flag {
		sort = sort + 1

		expire4.Id = 0
		expire4.ExpireType = 4
		expire4.DomainId = c.DomainId
		expire4.TenantId = tenantId
		expire4.Unit = 5
		//1秒 2分 3时 4天 5月 6年
		expire4.ExpireTime = 30
		expire4.CacheSet = 1
		expire4.Content = ""
		expire4.Sort = sort
		err = tx.Save(&expire4).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("save CacheExpireConfig error:%s \r\n", err)
			return err
		}
	}
	allFilePriority := 0

	expires := make([]domain.CacheExpireConfig, 0, 4)
	now := time.Now().Unix()
	for k, param := range c.Params {
		expire := domain.CacheExpireConfig{}
		if param.ExpireType == 4 {
			allFilePriority = param.Priority
		}
		expire.Id = param.Id
		if param.ExpireType == 4 {
			expire.Id = expire4.Id
		}

		expire.ExpireType = param.ExpireType
		expire.ExpireTime = param.ExpireTime
		expire.DomainId = c.DomainId
		expire.TenantId = param.TenantId
		expire.Unit = param.Unit
		expire.CacheSet = param.CacheSet
		expire.Content = param.Content
		expire.Sort = sort + k + 1
		expire.Priority = param.Priority
		expire.CreateTime = now
		expire.UpdateTime = now
		expires = append(expires, expire)
	}

	if len(expires) > 0 {
		err = tx.Save(&expires).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("save SaveMultiCacheExpireConfig error:%s \r\n", err)
			return err
		}
	}

	if allFilePriority > 0 {
		err = tx.Model(&domain.CacheExpireConfig{}).Where("expire_type=4 and domain_id=?", c.DomainId).Update("priority", allFilePriority).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("Update CacheExpireConfig error:%s \r\n", err)
			return err
		}

	}

	config := &domain.CacheExpireConfig{}
	err = tx.Model(&domain.CacheExpireConfig{}).Where("expire_type=4 and domain_id=?", c.DomainId).Find(&config).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get CacheExpireConfig error:%s \r\n", err)
		return err
	}

	if config.Sort >= cacheConfig.Sort {
		err = tx.Model(&domain.CacheExpireConfig{}).Where("expire_type=4 and domain_id=?", c.DomainId).Update("sort", sort+2).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("Update CacheExpireConfig error:%s \r\n", err)
			return err
		}
	}

	if !isSkip {
		ccEngineService := ccEngineService.CCEngineService{}
		ccEngineService.Log = e.Log
		//更新域名
		model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
		if err != nil {
			e.Log.Errorf("get DomainConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if model != nil {
			req := e.GenerateDomainReq(model)
			_, err = ccEngineService.UpdateDomain(&req)
			if err != nil {
				e.Log.Errorf("CreateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}

	//tx.Commit()
	return nil
}

func (e *DomainConfig) DeleteCacheExpireConfig(d *dto.CacheExpireConfigDeleteReq) error {

	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}
	var data domain.CacheExpireConfig

	db := tx.Model(&data).Delete(&data, d.Id)
	if err := db.Error; err != nil {
		e.Log.Errorf("DeleteCacheExpireConfig error:%s \r\n", err)
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: d.DomainId}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err := ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}

func (e *DomainConfig) SaveStateCodeExpireConfig(c *dto.StateCodeExpireConfigSaveReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}
	now := time.Now().Unix()
	code := domain.StateCodeExpireConfig{}
	code.Id = c.Id
	code.TenantId = c.TenantId
	code.DomainId = c.DomainId
	code.StateCode = c.StateCode
	code.ExpireTime = c.ExpireTime
	code.CreateTime = now
	code.UpdateTime = now
	err = tx.Save(&code).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save StateCodeExpireConfig error:%s \r\n", err)
		return err
	}
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err = ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	c.Id = code.Id

	tx.Commit()
	return nil
}

func (e *DomainConfig) DeleteStateCodeExpireConfig(d *dto.StateCodeExpireConfigDeleteReq) error {

	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}
	var data domain.StateCodeExpireConfig

	db := tx.Model(&data).Delete(&data, d.Id)
	if err := db.Error; err != nil {
		e.Log.Errorf("DeleteStateCodeExpireConfig error:%s \r\n", err)
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: d.DomainId}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err = ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("UpdateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}

func (e *DomainConfig) SaveMultiStateCodeExpireConfig(tx *gorm.DB, c *dto.MultiStateCodeExpireConfigSaveReq, isSkip bool) error {

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}

	err = tx.Model(&domain.StateCodeExpireConfig{}).Where("domain_id = ?", c.DomainId).Delete(&domain.StateCodeExpireConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete StateCodeExpireConfig error:%s \r\n", err)
		return err
	}
	now := time.Now().Unix()
	codes := make([]domain.StateCodeExpireConfig, 0, 5)
	for _, param := range c.Params {
		code := domain.StateCodeExpireConfig{}
		code.TenantId = param.TenantId
		code.DomainId = param.DomainId
		code.StateCode = param.StateCode
		code.ExpireTime = param.ExpireTime
		code.CreateTime = now
		codes = append(codes, code)
	}

	err = tx.Save(&codes).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save StateCodeExpireConfig error:%s \r\n", err)
		return err
	}

	if !isSkip {
		ccEngineService := ccEngineService.CCEngineService{}
		ccEngineService.Log = e.Log
		//更新域名
		model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
		if err != nil {
			e.Log.Errorf("get DomainConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if model != nil {
			req := e.GenerateDomainReq(model)
			_, err = ccEngineService.UpdateDomain(&req)
			if err != nil {
				e.Log.Errorf("CreateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}

	//tx.Commit()
	return nil
}

func (e *DomainConfig) SaveAntiTheftConfig(tx *gorm.DB, c *dto.AntiTheftConfigSaveReq, isSkip bool) error {

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}
	config := domain.AntiTheftConfig{}
	now := time.Now().Unix()
	config.Id = c.Id
	config.DomainId = c.DomainId
	config.TenantId = c.TenantId
	config.EnableWhite = c.EnableWhite
	config.EnableBlack = c.EnableBlack
	config.WhiteList = c.WhiteList
	config.BlackList = c.BlackList
	config.EnableIpControl = c.EnableIpController
	config.EnableUaControl = c.EnableUaController
	config.IpType = c.IpType
	config.UaType = c.UaType
	config.IpList = c.IpList
	config.UaList = c.UaList
	config.IncludeEmpty = c.IncludeEmpty
	if c.Id > 0 {
		config.UpdateTime = time.Now().Unix()
	} else {
		config.CreateTime = now
		config.UpdateTime = now
	}
	err = tx.Save(&config).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save CacheExpireConfig error:%s \r\n", err)
		return err
	}

	if !isSkip {
		ccEngineService := ccEngineService.CCEngineService{}
		ccEngineService.Log = e.Log
		//更新域名
		model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
		if err != nil {
			e.Log.Errorf("get DomainConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if model != nil {
			req := e.GenerateDomainReq(model)
			_, err = ccEngineService.UpdateDomain(&req)
			if err != nil {
				e.Log.Errorf("UpdateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}
	c.Id = config.Id

	//tx.Commit()
	return nil
}

func (e *DomainConfig) SaveUrlSign(tx *gorm.DB, c *dto.UrlSignSaveReq, isSkip bool) error {

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("域名不存在")
	}
	config := domain.UrlSign{}
	now := time.Now().Unix()
	config.Id = c.Id
	config.DomainId = c.DomainId
	config.TenantId = c.TenantId
	config.SignStatus = c.SignStatus
	config.SignType = c.SignType
	config.KeyList = c.Keys
	config.SessionTimeout = c.SessionTimeout
	config.SignArg = c.SignArg
	config.SignMethod = c.SignMethod
	if c.Id > 0 {
		config.UpdateTime = time.Now().Unix()
	} else {
		config.CreateTime = now
		config.UpdateTime = now
	}
	err = tx.Save(&config).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save CacheExpireConfig error:%s \r\n", err)
		return err
	}

	if !isSkip {

		ccEngineService := ccEngineService.CCEngineService{}
		ccEngineService.Log = e.Log
		//更新域名
		model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
		if err != nil {
			e.Log.Errorf("get DomainConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if model != nil {
			req := e.GenerateDomainReq(model)
			_, err = ccEngineService.UpdateDomain(&req)
			if err != nil {
				e.Log.Errorf("UpdateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}
	c.Id = config.Id

	//tx.Commit()
	return nil
}

func (e *DomainConfig) SaveCacheFilterConfig(c *dto.CacheFilterConfigSaveReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}

	//获取最后一个记录
	var cacheFilter domain.CacheFilterConfig
	tx.Model(&domain.CacheFilterConfig{}).Order("sort desc").First(&cacheFilter)

	filters := make([]domain.CacheFilterConfig, 0, 5)
	err = tx.Model(&domain.CacheFilterConfig{}).Where("domain_id=?", c.DomainId).Find(&filters).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get CacheExpireConfig error:%s \r\n", err)
		return err
	}
	//判断有没有全部文件类型 没有添加
	flag := false
	for _, filter := range filters {
		if filter.ExpireType == 4 {
			flag = true
		}
	}
	filter4 := domain.CacheFilterConfig{}
	if !flag {
		filter4.Id = 0
		filter4.ExpireType = 4
		filter4.IgnoreFilter = 1
		//expire.ExpireTime = c.ExpireTime
		filter4.DomainId = c.DomainId
		filter4.TenantId = c.TenantId
		filter4.Sort = cacheFilter.Sort + 1
		filter4.FilterParam = ""
		//expire.Unit = c.Unit
		//1秒 2分 3时 4天 5月 6年
		//filter.ExpireTime = 60 * 60 * 24 * 30
		//filter.CacheSet = c.CacheSet
		filter4.Content = ""
		err = tx.Save(&filter4).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("save CacheFilterConfig error:%s \r\n", err)
			return err
		}
	}

	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}
	filter := domain.CacheFilterConfig{}
	now := time.Now().Unix()
	filter.Id = c.Id
	filter.TenantId = c.TenantId
	filter.DomainId = c.DomainId
	filter.IgnoreFilter = c.IgnoreFilter
	filter.FilterParam = c.FilterParam
	filter.ExpireType = c.ExpireType
	filter.Content = c.Content
	filter.IgnoreCase = c.IgnoreCase
	filter.DomainId = c.DomainId
	filter.Priority = c.Priority
	if c.Id > 0 {
		filter.Sort = c.Sort
		filter.UpdateTime = now
	} else {
		filter.Sort = cacheFilter.Sort + 1
		filter.CreateTime = now
		filter.UpdateTime = now
	}

	err = tx.Save(&filter).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save CacheFilterConfig error:%s \r\n", err)
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err := ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	c.Id = filter.Id
	tx.Commit()
	return nil
}

func (e *DomainConfig) DeleteCacheFilterConfig(d *dto.CacheFilterConfigDeleteReq) error {

	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}
	var data domain.CacheFilterConfig

	db := tx.Model(&data).Delete(&data, d.Id)
	if err := db.Error; err != nil {
		tx.Rollback()
		e.Log.Errorf("DeleteCacheFilterConfig error:%s \r\n", err)
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: d.DomainId}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err := ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}

func (e *DomainConfig) SaveMultiCacheFilterConfig(tx *gorm.DB, c *dto.MultiCacheFilterConfigSaveReq, isSkip bool) error {

	tenantId := ""
	if len(c.Params) > 0 {
		tenantId = c.Params[0].TenantId
	}

	for _, param := range c.Params {
		if len(param.Content) <= 0 && param.ExpireType != 4 {
			return errors.New("过滤参数内容不能为空")
		}
		if param.IgnoreFilter <= 0 || param.IgnoreFilter > 4 {
			return errors.New("忽略参数取之范围不对")
		}
		if param.IgnoreFilter == 3 || param.IgnoreFilter == 4 {
			if len(param.FilterParam) <= 0 {
				return errors.New("指定参数不能为空")
			}
		}
		if param.ExpireType == 4 {
			if len(param.Content) > 0 && param.Content != "/" {
				return errors.New("匹配类型为全部文件时不能设置匹配内容")
			}
		}

	}

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		tx.Rollback()
		return errors.New("加速域名不存在")
	}

	err = tx.Model(&domain.CacheFilterConfig{}).Where("domain_id=?", c.DomainId).Delete(&domain.CacheFilterConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete CacheFilterConfig error:%s \r\n", err)
		return err
	}

	tempFilters := make([]domain.CacheFilterConfig, 0, 5)
	err = tx.Model(&domain.CacheFilterConfig{}).Where("domain_id=?", c.DomainId).Find(&tempFilters).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get CacheExpireConfig error:%s \r\n", err)
		return err
	}
	//判断有没有全部文件类型 没有添加
	flag := false
	for _, filter := range tempFilters {
		if filter.ExpireType == 4 {
			flag = true
		}
	}
	filter4 := domain.CacheFilterConfig{}
	if !flag {
		filter4.Id = 0
		filter4.ExpireType = 4
		filter4.IgnoreFilter = 1
		//expire.ExpireTime = c.ExpireTime
		filter4.DomainId = c.DomainId
		filter4.TenantId = tenantId
		filter4.Sort = 0
		filter4.FilterParam = ""
		//expire.Unit = c.Unit
		//1秒 2分 3时 4天 5月 6年
		//filter.ExpireTime = 60 * 60 * 24 * 30
		//filter.CacheSet = c.CacheSet
		filter4.Content = ""
		err = tx.Save(&filter4).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("save CacheFilterConfig error:%s \r\n", err)
			return err
		}

	}
	allFilePriority := 0
	filters := make([]domain.CacheFilterConfig, 0, 4)
	now := time.Now().Unix()
	for _, param := range c.Params {
		if len(param.Content) <= 0 && param.ExpireType != 4 {
			tx.Rollback()
			return errors.New("过滤参数内容不能为空")
		}
		if param.IgnoreFilter <= 0 || param.IgnoreFilter > 4 {
			tx.Rollback()
			return errors.New("忽略参数取之范围不对")
		}

		if param.IgnoreFilter == 3 || param.IgnoreFilter == 4 {
			if len(param.FilterParam) <= 0 {
				tx.Rollback()
				return errors.New("指定参数不能为空")
			}
		}
		filter := domain.CacheFilterConfig{}
		if param.ExpireType == 4 {
			if len(param.Content) > 0 && param.Content != "/" {
				tx.Rollback()
				return errors.New("匹配类型为全部文件时不能设置匹配内容")
			}
			allFilePriority = param.Priority
		}
		filter.Id = param.Id
		if param.ExpireType == 4 {
			filter.Id = filter4.Id
		}

		filter.TenantId = param.TenantId
		filter.DomainId = c.DomainId
		filter.IgnoreFilter = param.IgnoreFilter
		filter.FilterParam = param.FilterParam
		filter.IgnoreCase = param.IgnoreCase
		filter.ExpireType = param.ExpireType
		filter.Content = param.Content
		filter.DomainId = c.DomainId
		filter.Priority = param.Priority
		filter.CreateTime = now
		filter.UpdateTime = now
		filters = append(filters, filter)
	}

	if len(filters) > 0 {
		err = tx.Save(&filters).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("save SaveMultiCacheFilterConfig error:%s \r\n", err)
			return err
		}
	}

	if allFilePriority > 0 {
		err = tx.Model(&domain.CacheFilterConfig{}).Where("expire_type=4 and domain_id=?", c.DomainId).Update("priority", allFilePriority).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("Update CacheExpireConfig error:%s \r\n", err)
			return err
		}
	}

	if !isSkip {
		ccEngineService := ccEngineService.CCEngineService{}
		ccEngineService.Log = e.Log
		//更新域名
		model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
		if err != nil {
			e.Log.Errorf("get DomainConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if model != nil {
			req := e.GenerateDomainReq(model)
			_, err = ccEngineService.UpdateDomain(&req)
			if err != nil {
				e.Log.Errorf("CreateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}

	//tx.Commit()
	return nil
}

func (e *DomainConfig) SaveDistributionProtocol(tx *gorm.DB, c *dto.DistributionProtocolSaveReq, isSkip bool) error {

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}

	if c.EnableQuic == 1 || c.EnableHttps == 1 {
		if domainConfig.CertificateId <= 0 {
			tx.Rollback()
			return errors.New("启用HTTPS必须先关联证书")
		}
	}
	if c.EnableHttps == 2 {
		c.ForceJump = 0
		c.EnableHttps = 2
		c.EnableQuic = 2
		c.RedirectCode = 0
		c.EnableHttp2 = 2
		c.TlsVersion = ""
	}

	d := domain.DistributionProtocol{}
	now := time.Now().Unix()
	d.Model.Id = c.Id
	d.DomainId = c.DomainId
	d.EnableHttps = c.EnableHttps
	d.EnableQuic = c.EnableQuic
	d.ForceJump = c.ForceJump
	d.EnableHttp2 = c.EnableHttp2
	d.TenantId = c.TenantId
	d.RedirectCode = c.RedirectCode
	d.TlsVersion = c.TlsVersion

	if c.Id > 0 {
		d.UpdateTime = now
	} else {
		d.CreateTime = now
		d.UpdateTime = now
	}
	err = tx.Save(&d).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("save CacheFilterConfig error:%s \r\n", err)
		return err
	}
	if !isSkip {
		ccEngineService := ccEngineService.CCEngineService{}
		ccEngineService.Log = e.Log
		//更新域名
		model, err := e.Get(&dto.DomainConfigGetReq{Id: c.DomainId}, tx)
		if err != nil {
			e.Log.Errorf("get DomainConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if model != nil {
			req := e.GenerateDomainReq(model)
			_, err := ccEngineService.UpdateDomain(&req)
			if err != nil {
				e.Log.Errorf("CreateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}

	c.Id = d.Id
	//tx.Commit()
	return nil
}

func (e *DomainConfig) DeleteDistributionProtocol(d *dto.DistributionProtocolDeleteReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}
	var data domain.DistributionProtocol

	db := tx.Model(&data).Delete(&data, d.Id)
	if err := db.Error; err != nil {
		tx.Rollback()
		e.Log.Errorf("DeleteCacheFilterConfig error:%s \r\n", err)
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: d.DomainId}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err := ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("CreateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	return nil
}

func (e *DomainConfig) GenerateDomainReq(model *domain.DomainConfigModel) ccenginDto.DomainReq {
	req := ccenginDto.DomainReq{}
	req.Name = ""
	//域名配置
	if model.DomainConfig.Id > 0 {
		req.Id = model.DomainConfig.DomainTaskId
		req.TenantId = model.DomainConfig.TenantId
		req.Domain = model.DomainConfig.AcDomain
		req.ServiceType = serviceTypeMap[model.DomainConfig.AcType]
		req.Area = areaMap[model.DomainConfig.AcArea]
	}

	//协议分发配置
	if model.DistributionProtocol.Id > 0 {
		forceDirect := ccenginDto.ForceRedirect{}
		if model.DistributionProtocol.ForceJump == 0 {
			forceDirect.Enable = 0
		} else {
			forceDirect.Enable = 1
		}

		if model.DistributionProtocol.ForceJump == 1 {
			forceDirect.RedirectType = "https"
		} else {
			forceDirect.RedirectType = "http"
		}

		if model.DistributionProtocol.EnableHttps == 1 {
			//forceDirect.Enable = 1
			req.Https.Enable = 1
		} else {
			//forceDirect.Enable = 0
			req.Https.Enable = 0
		}

		if model.DistributionProtocol.EnableHttp2 == 1 {
			//forceDirect.Enable = 1
			req.Https.Http2 = 1
		} else {
			//forceDirect.Enable = 0
			req.Https.Http2 = 0
		}
		forceDirect.RedirectCode = model.DistributionProtocol.RedirectCode
		forceDirect.RedirectType = redirectTypeMap[model.DistributionProtocol.ForceJump]
		req.ForceRedirect = forceDirect
		req.Advance.TlsVersion = model.DistributionProtocol.TlsVersion

		quic := ccenginDto.Quic{}
		if model.DistributionProtocol.EnableQuic == 1 {
			quic.Enable = 1
		} else {
			quic.Enable = 0
		}
		req.Quic = quic
	}

	//证书配置
	if model.Certificate.Id > 0 {
		certInfo := ccenginDto.CertInfo{}
		certInfo.CertId = model.Certificate.CertificateId
		certInfo.Certificate = model.Certificate.PublicKey
		certInfo.PrivateKey = model.Certificate.PrivateKey
		//req.Https.Http2 = 0
		req.Https.CertInfo = certInfo
	}

	if model.BackSourceConfig.Id > 0 {
		req.Advance.Ipv6Accelerate = model.BackSourceConfig.Ipv6Accelerate
		req.Advance.OriginTimeout = model.BackSourceConfig.OriginTimeout
	}
	//源站配置
	if model.SourceStationConfigs != nil && len(model.SourceStationConfigs) > 0 {
		origins := make([]string, 0, 5)
		backOrigins := make([]string, 0, 5)
		originMap := make(map[int][]domain.SourceStationConfig)
		backOriginMap := make(map[int][]domain.SourceStationConfig)
		indexMap := make(map[int]struct{})
		for _, v := range model.SourceStationConfigs {
			v := v
			indexMap[v.Index] = struct{}{}
			weight := "1"
			if v.Weight > 0 {
				weight = strconv.Itoa(v.Weight)
			}
			ip := v.SourceStationIp + ":" + v.Port + ":" + weight
			if v.Priority == 1 {
				o, ok := originMap[v.Index]
				if !ok {
					o = make([]domain.SourceStationConfig, 0, 3)
				}
				o = append(o, v)
				originMap[v.Index] = o
				origins = append(origins, ip)
			} else {
				b, ok := backOriginMap[v.Index]
				if !ok {
					b = make([]domain.SourceStationConfig, 0, 3)
				}
				b = append(b, v)
				backOriginMap[v.Index] = b
				backOrigins = append(backOrigins, ip)
			}
		}

		//req.Origin.Origins = origins
		//req.Origin.BackupOrigins = backOrigins
		flag := net.ParseIP((model.SourceStationConfigs)[0].SourceStationIp)
		if flag != nil {
			req.Origin.OriginType = "ip"
			req.Origin.BackupOriginType = "ip"
		} else {
			req.Origin.OriginType = "domain"
			req.Origin.BackupOriginType = "domain"
		}
		if model.BackSourceConfig.Id > 0 {
			if model.BackSourceConfig.Protocol == 1 {
				req.Origin.OriginPullProtocol = "http"
			} else if model.BackSourceConfig.Protocol == 2 {
				req.Origin.OriginPullProtocol = "https"
			} else {
				req.Origin.OriginPullProtocol = "follow"
			}
			req.Origin.OriginArea = model.BackSourceConfig.Area
			req.Origin.OriginHost = model.BackSourceConfig.Host

			req.Advance.ForceRedirectionEnable = strconv.Itoa(model.BackSourceConfig.EnableTrace)
		}
		req.Advance.Range.Enable = model.DomainConfig.Range

		originInfos := make([]ccenginDto.OriginInfo, 0, 2)
		originInfo := ccenginDto.OriginInfo{}
		for index, _ := range indexMap {
			matchType := ""
			matchRule := ""
			servers := make([]ccenginDto.Server, 0, 5)
			standByServers := make([]ccenginDto.StandByServer, 0, 5)
			for _, origin := range originMap[index] {
				origin := origin
				weight := "1"
				if origin.Weight > 0 {
					weight = strconv.Itoa(origin.Weight)
				}
				ip := origin.SourceStationIp + ":" + origin.Port + ":" + weight
				server := ccenginDto.Server{}
				server.Target = ip
				server.OriginType = req.Origin.OriginType
				server.OriginPullProtocol = req.Origin.OriginPullProtocol
				server.OriginHost = origin.OriginHost
				matchType = origin.MatchType
				matchRule = origin.MatchRule
				servers = append(servers, server)
			}
			originInfo.Servers = servers
			originInfo.MatchType = matchType
			originInfo.MatchRule = matchRule

			for _, backOrigin := range backOriginMap[index] {
				backOrigin := backOrigin
				weight := "1"
				if backOrigin.Weight > 0 {
					weight = strconv.Itoa(backOrigin.Weight)
				}
				ip := backOrigin.SourceStationIp + ":" + backOrigin.Port + ":" + weight
				server := ccenginDto.StandByServer{}
				server.Target = ip
				server.OriginType = req.Origin.OriginType
				server.OriginPullProtocol = req.Origin.OriginPullProtocol
				server.OriginHost = backOrigin.OriginHost
				matchType = backOrigin.MatchType
				matchRule = backOrigin.MatchRule
				standByServers = append(standByServers, server)
			}
			originInfo.StandByServer = standByServers
			originInfo.MatchType = matchType
			originInfo.MatchRule = matchRule
			originInfos = append(originInfos, originInfo)
		}
		req.Origin.OriginInfos = originInfos

	}

	//状态码过期设置
	req.Advance.SpecialCacheCodeList = make([]ccenginDto.SpecialCacheCode, 0, 5)
	if model.StateCodeExpireConfigs != nil && len(model.StateCodeExpireConfigs) > 0 {
		specialCodes := make([]ccenginDto.SpecialCacheCode, 0, 3)
		for _, v := range model.StateCodeExpireConfigs {
			v := v
			specialCode := ccenginDto.SpecialCacheCode{}
			specialCode.Code = v.StateCode
			specialCode.Expiration = strconv.Itoa(v.ExpireTime) + "s"
			specialCodes = append(specialCodes, specialCode)
		}
		req.Advance.SpecialCacheCodeList = specialCodes
	}

	//过期时间配置
	cacheRules := make([]ccenginDto.CacheRule, 0, 5)
	req.Cache.CacheRules = cacheRules
	if model.CacheExpireConfigs != nil && len(model.CacheExpireConfigs) > 0 {

		for _, v := range model.CacheExpireConfigs {
			////遵循源站不走接口
			//if v.CacheSet == 3 {
			//	continue
			//}
			v := v
			cacheRule := ccenginDto.CacheRule{}
			cacheRule.CacheType = cacheTypeMap[v.ExpireType]
			cacheRule.CacheContents = v.Content
			cacheRule.Unit = unitMap[v.Unit]
			cacheRule.CacheTime = v.ExpireTime
			cacheRule.FollowOrigin = "off"
			//遵循源站是on
			if v.CacheSet == 3 || v.CacheSet == 2 {
				cacheRule.FollowOrigin = "on"
			}
			req.Cache.CacheRules = append(req.Cache.CacheRules, cacheRule)
		}
		req.Cache.IgnoreCacheControl = "off"
	}
	//过滤参数配置
	queryStrings := make([]ccenginDto.QueryString, 0, 5)
	req.CacheKey.QueryString = queryStrings
	if model.CacheFilterConfigs != nil {
		req.CacheKey.FullUrlCache = "off"
		for _, v := range model.CacheFilterConfigs {
			queryString := ccenginDto.QueryString{}
			queryString.CacheType = cacheTypeMap[v.ExpireType]
			queryString.CacheContents = v.Content
			queryString.Action = filterTypeMap[v.IgnoreFilter]
			queryString.Value = v.FilterParam
			req.CacheKey.QueryString = append(req.CacheKey.QueryString, queryString)
		}

		if len(queryStrings) > 0 {
			req.CacheKey.FullUrlCache = "on"
		} else {
			req.CacheKey.FullUrlCache = "off"
		}
		//req.CacheKey.QueryString = queryStrings
	}

	//防盗链设置
	if model.AntiTheftConfig.Id > 0 {
		req.RefererFilter.WhitelistEnable = model.AntiTheftConfig.EnableWhite
		req.RefererFilter.BlacklistEnable = model.AntiTheftConfig.EnableBlack
		wList := strings.Split(model.AntiTheftConfig.WhiteList, "^^")
		req.RefererFilter.Whitelist = wList
		bList := strings.Split(model.AntiTheftConfig.BlackList, "^^")
		req.RefererFilter.Blacklist = bList
		req.Advance.IpControl.Enable = model.AntiTheftConfig.EnableIpControl
		req.Advance.UaControl.Enable = model.AntiTheftConfig.EnableUaControl
		req.Advance.IpControl.Type = model.AntiTheftConfig.IpType
		req.Advance.UaControl.Type = model.AntiTheftConfig.UaType
		ipList := strings.Split(model.AntiTheftConfig.IpList, "^^")
		req.Advance.IpControl.Ips = ipList
		uaList := strings.Split(model.AntiTheftConfig.UaList, "^^")
		req.Advance.UaControl.UaList = uaList
		if model.AntiTheftConfig.IncludeEmpty == 1 {
			req.RefererFilter.IncludeEmpty = true
		} else {
			req.RefererFilter.IncludeEmpty = false
		}

	}

	if model.UrlSign.Id > 0 {
		req.Advance.UrlSign.Status = model.UrlSign.SignStatus
		req.Advance.UrlSign.SessionTimeout = model.UrlSign.SessionTimeout
		req.Advance.UrlSign.Type = model.UrlSign.SignType
		req.Advance.UrlSign.SignMethod = model.UrlSign.SignMethod
		signList := strings.Split(model.UrlSign.KeyList, "^^")
		req.Advance.UrlSign.Keys = signList
		req.Advance.UrlSign.SignArg = model.UrlSign.SignArg
	}
	req.Advance.CdnRequestHeaderPolicy = make([]ccenginDto.CdnRequestHeaderPolicy, 0, 3)
	if len(model.RequestHeaderConfigs) > 0 {
		for _, header := range model.RequestHeaderConfigs {
			requestHeader := ccenginDto.CdnRequestHeaderPolicy{}
			requestHeader.NewHeaderKey = header.HeaderKey
			requestHeader.NewHeaderValue = header.HeaderValue
			requestHeader.Type = header.OperatorType
			req.Advance.CdnRequestHeaderPolicy = append(req.Advance.CdnRequestHeaderPolicy, requestHeader)
		}
	}

	req.Advance.CdnResponseHeaderPolicy = make([]ccenginDto.CdnResponseHeaderPolicy, 0, 3)
	if len(model.ResponseHeaderConfigs) > 0 {
		for _, header := range model.ResponseHeaderConfigs {
			responseHeader := ccenginDto.CdnResponseHeaderPolicy{}
			responseHeader.NewHeaderKey = header.HeaderKey
			responseHeader.NewHeaderValue = header.HeaderValue
			responseHeader.Type = header.OperatorType
			req.Advance.CdnResponseHeaderPolicy = append(req.Advance.CdnResponseHeaderPolicy, responseHeader)
		}
	}
	if model.CompressConfig.Id > 0 {
		req.Advance.Compress.FileType = model.CompressConfig.FileType
		req.Advance.Compress.Status = model.CompressConfig.CompressState
		req.Advance.Compress.Type = model.CompressConfig.CompressType
	}
	return req
}

func (e *DomainConfig) StartDomain(d *dto.StartDomainReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	config := &domain.DomainConfig{}
	err := tx.Model(&domain.DomainConfig{}).Where("id=?", d.Id).Find(&config).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	err = ccEngineService.StartDomain(&ccenginDto.DomainReq{Id: config.DomainTaskId, TenantId: d.TenantId})
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("StartDomain error:%s \r\n", err)
		return err
	}

	now := time.Now().Unix()
	param := make(map[string]interface{})
	param["domain_state"] = 2
	param["update_time"] = now
	err = tx.Model(&domain.DomainConfig{}).Where("id=?", config.Id).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("UpdateDomain error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func (e *DomainConfig) StopDomain(d *dto.StopDomainReq) error {
	tx := e.Orm.Begin()
	defer func() {
		if r := recover(); r != nil {
			tx.Rollback()
		}
	}()
	if err := tx.Error; err != nil {
		return err
	}

	config := &domain.DomainConfig{}
	err := tx.Model(&domain.DomainConfig{}).Where("id=?", d.Id).Find(&config).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	err = ccEngineService.StopDomain(&ccenginDto.DomainReq{Id: config.DomainTaskId, TenantId: d.TenantId})
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("StopDomain error:%s \r\n", err)
		return err
	}

	now := time.Now().Unix()
	param := make(map[string]interface{})
	param["domain_state"] = 3
	param["update_time"] = now
	err = tx.Model(&domain.DomainConfig{}).Where("id=?", config.Id).Updates(&param).Error
	if err != nil {
		e.Log.Errorf("UpdateDomain error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

// RecordUpOrDown 上移下移
func (e *DomainConfig) RecordUpOrDown(d *dto.UpOrDownReq) error {
	var data domain.CacheFilterConfig
	var compareData domain.CacheFilterConfig
	tx := e.Orm.Begin()

	//获取当前数据
	e.Orm.First(&data, d.Id)
	if data.Id <= 0 {
		return nil
	}
	if d.Type == 1 {
		//获取上一条数据
		e.Orm.Where("sort<?", data.Sort).Order("sort desc").Limit(1).Find(&compareData)
	} else {
		//获取下一条数据
		e.Orm.Where("sort>?", data.Sort).Order("sort asc").Limit(1).Find(&compareData)
	}
	now := time.Now().Unix()
	data.Sort, compareData.Sort = compareData.Sort, data.Sort
	err := tx.Model(&domain.CacheFilterConfig{}).Where("id=?", data.Id).Updates(map[string]interface{}{"sort": data.Sort, "update_time": now}).Error
	if err != nil {
		e.Log.Errorf("update CacheFilterConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	err = tx.Model(&domain.CacheFilterConfig{}).Where("id=?", compareData.Id).Updates(map[string]interface{}{"sort": compareData.Sort, "update_time": now}).Error
	if err != nil {
		e.Log.Errorf("update CacheFilterConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func (e *DomainConfig) CacheRecordUpOrDown(d *dto.UpOrDownReq) error {
	var data domain.CacheExpireConfig
	var compareData domain.CacheExpireConfig
	tx := e.Orm.Begin()

	//获取当前数据
	e.Orm.First(&data, d.Id)
	if data.Id <= 0 {
		return nil
	}
	if d.Type == 1 {
		//获取上一条数据
		e.Orm.Where("sort<? and domain_id=?", data.Sort, data.DomainId).Order("sort desc").Limit(1).Find(&compareData)
	} else {
		//获取下一条数据
		e.Orm.Where("sort>?and domain_id=?", data.Sort, data.DomainId).Order("sort asc").Limit(1).Find(&compareData)
	}
	//now := time.Now().Unix()
	data.Sort, compareData.Sort = compareData.Sort, data.Sort
	err := tx.Model(&domain.CacheExpireConfig{}).Where("id=?", data.Id).Updates(map[string]interface{}{"sort": data.Sort}).Error
	if err != nil {
		e.Log.Errorf("update CacheExpireConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	err = tx.Model(&domain.CacheExpireConfig{}).Where("id=?", compareData.Id).Updates(map[string]interface{}{"sort": compareData.Sort}).Error
	if err != nil {
		e.Log.Errorf("update CacheExpireConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}

	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	//更新域名
	model, err := e.Get(&dto.DomainConfigGetReq{Id: data.DomainId}, tx)
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	if model != nil {
		req := e.GenerateDomainReq(model)
		_, err := ccEngineService.UpdateDomain(&req)
		if err != nil {
			e.Log.Errorf("UpdateDomain error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	tx.Commit()
	return nil
}

func (e *DomainConfig) DomainOwnerVerify(d *ccenginDto.VerifyReq) (*ccenginDto.VerifyRes, error) {
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	res, err := ccEngineService.DomainOwnerVerify(d)
	if err != nil {
		e.Log.Errorf("DomainOwnerVerify error:%s \r\n", err)
		return nil, err
	}
	return res, nil
}

func (e *DomainConfig) DomainOwnerVerify2(d *ccenginDto.VerifyReq2) (*ccenginDto.VerifyRes, error) {
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	domainConfig := &domain.DomainConfig{}
	err := e.Orm.Model(&domain.DomainConfig{}).Where("id=?", d.Id).Find(&domainConfig).Error
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return nil, err
	}
	d.TenantId = domainConfig.TenantId
	d.TaskId = domainConfig.DomainTaskId
	res, err := ccEngineService.DomainOwnerVerify2(d)
	if err != nil {
		e.Log.Errorf("DomainOwnerVerify2 error:%s \r\n", err)
		return nil, err
	}
	return res, nil
}

func (e *DomainConfig) SaveOverWriteUrl(d *ccenginDto.OriginUrlRewriteReq) error {

	tx := e.Orm.Begin()
	overWriteUrl := domain.OverWriteUrl{}

	if d.Id <= 0 {
		var maxSort int
		result := e.Orm.Model(&domain.OverWriteUrl{}).Where("domain_id=? and overwrite_type=?", d.DomainId, d.OverWriteType).Select("MAX(sort)").Row()
		result.Scan(&maxSort)
		overWriteUrl.Sort = maxSort + 1
	} else {
		err := e.Orm.Model(&domain.OverWriteUrl{}).Where("id=?", d.Id).Find(&overWriteUrl).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("get SaveOverWriteUrl error:%s \r\n", err)
			return err
		}
	}
	overWriteUrl.Id = d.Id
	overWriteUrl.TenantId = d.TenantId
	overWriteUrl.DomainId = d.DomainId
	overWriteUrl.OriginUrl = d.OriginUrl
	overWriteUrl.DestHost = d.DestHost
	overWriteUrl.DestPath = d.DestPath
	overWriteUrl.OverwriteKind = d.OverwriteKind
	overWriteUrl.ExactlyMatch = d.ExactlyMatch
	overWriteUrl.OverwriteType = d.OverWriteType
	err := tx.Save(&overWriteUrl).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("SaveOverWriteUrl error:%s \r\n", err)
		return err
	}

	overWriteUrls := make([]domain.OverWriteUrl, 0, 4)
	err = tx.Model(&domain.OverWriteUrl{}).Where("domain_id=? and overwrite_type=?", d.DomainId, d.OverWriteType).Find(&overWriteUrls).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get SaveOverWriteUrl error:%s \r\n", err)
		return err
	}
	basic := domain.DomainConfig{}
	err = tx.Model(&domain.DomainConfig{}).Where("id=?", d.DomainId).Find(&basic).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	req := ccenginDto.SaveUrlRewriteReq{}
	req.DomainTaskId = basic.DomainTaskId
	req.TenantId = basic.TenantId
	urlRewrites := make([]ccenginDto.UrlRewrite, 0, 4)
	for _, url := range overWriteUrls {
		urlRewrite := ccenginDto.UrlRewrite{}
		urlRewrite.Origin = url.OriginUrl
		urlRewrite.Dest = url.DestHost + url.DestPath
		urlRewrite.ExactlyMatch = url.ExactlyMatch
		urlRewrite.Type = url.OverwriteKind
		urlRewrites = append(urlRewrites, urlRewrite)
	}
	fmt.Println("KKKKKKKKK：", urlRewrites)
	req.UrlRewrites = urlRewrites
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	if d.OverWriteType == 1 {
		err = ccEngineService.OriginUrlRewrite(&req)
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("OriginUrlRewrite error:%s \r\n", err)
			return err
		}
	} else {
		err = ccEngineService.RequestUrlRewrite(&req)
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("RequestUrlRewrite error:%s \r\n", err)
			return err
		}
	}

	tx.Commit()
	return nil
}

func (e *DomainConfig) GetOverWriteUrl(d *ccenginDto.GetOriginUrlRewriteReq) error {
	overWriteUrls := make([]domain.OverWriteUrl, 0, 4)
	err := e.Orm.Model(&domain.OverWriteUrl{}).Where("domain_id=? and overwrite_type=?", d.DomainId, d.OverWriteType).Find(&overWriteUrls).Error
	if err != nil {
		e.Log.Errorf("get SaveOverWriteUrl error:%s \r\n", err)
		return err
	}

	basic := domain.DomainConfig{}
	err = e.Orm.Model(&domain.DomainConfig{}).Where("id=?", d.DomainId).Find(&basic).Error
	if err != nil {
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	req := ccenginDto.GetUrlRewriteReq{}
	req.DomainTaskId = basic.DomainTaskId
	req.TenantId = basic.TenantId
	urlRewrites := make([]ccenginDto.UrlRewrite, 0, 4)
	for _, url := range overWriteUrls {
		urlRewrite := ccenginDto.UrlRewrite{}
		urlRewrite.Origin = url.OriginUrl
		urlRewrite.Dest = url.DestHost + url.DestPath
		urlRewrite.ExactlyMatch = url.ExactlyMatch
		urlRewrites = append(urlRewrites, urlRewrite)
	}
	req.UrlRewrites = urlRewrites
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	if d.OverWriteType == 1 {
		err = ccEngineService.GetOriginUrlRewrite(&req)
		if err != nil {
			e.Log.Errorf("OriginUrlRewrite error:%s \r\n", err)
			return err
		}
	} else {
		err = ccEngineService.GetRequestUrlRewrite(&req)
		if err != nil {
			e.Log.Errorf("RequestUrlRewrite error:%s \r\n", err)
			return err
		}
	}

	return nil
}

func (e *DomainConfig) DeleteOverWriteUrl(d *ccenginDto.DeleteUrlRewriteReq) error {

	tx := e.Orm.Begin()
	err := tx.Model(&domain.OverWriteUrl{}).Where("id in ?", d.Ids).Delete(&domain.OverWriteUrl{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("DeleteOverWriteUrl error:%s \r\n", err)
		return err
	}
	overWriteUrls := make([]domain.OverWriteUrl, 0, 4)
	err = tx.Model(&domain.OverWriteUrl{}).Where("domain_id=? and overwrite_type=?", d.DomainId, d.OverWriteType).Find(&overWriteUrls).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get SaveOverWriteUrl error:%s \r\n", err)
		return err
	}
	basic := domain.DomainConfig{}
	err = tx.Model(&domain.DomainConfig{}).Where("id=?", d.DomainId).Find(&basic).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	req := ccenginDto.SaveUrlRewriteReq{}
	req.DomainTaskId = basic.DomainTaskId
	req.TenantId = basic.TenantId
	urlRewrites := make([]ccenginDto.UrlRewrite, 0, 4)
	for _, url := range overWriteUrls {
		urlRewrite := ccenginDto.UrlRewrite{}
		urlRewrite.Origin = url.OriginUrl
		urlRewrite.Dest = url.DestHost + url.DestPath
		urlRewrite.ExactlyMatch = url.ExactlyMatch
		urlRewrite.Type = url.OverwriteKind
		urlRewrites = append(urlRewrites, urlRewrite)
	}
	req.UrlRewrites = urlRewrites
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	if d.OverWriteType == 1 {
		err = ccEngineService.OriginUrlRewrite(&req)
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("OriginUrlRewrite error:%s \r\n", err)
			return err
		}
	} else {
		err = ccEngineService.RequestUrlRewrite(&req)
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("RequestUrlRewrite error:%s \r\n", err)
			return err
		}
	}
	tx.Commit()
	return nil
}

func (e *DomainConfig) MoveView(d *ccenginDto.MoveDown) error {
	var data domain.OverWriteUrl
	var compareData domain.OverWriteUrl
	tx := e.Orm.Begin()

	//获取当前数据
	e.Orm.First(&data, d.Id)
	if data.Id <= 0 {
		return nil
	}
	if d.Type == 1 {
		//获取上一条数据
		err := tx.Where("sort<? and overwrite_type=? and domain_id =?", data.Sort, d.OverWriteType, d.DomainId).Order("sort desc").Limit(1).Find(&compareData).Error
		if err != nil {
			e.Log.Errorf("MoveView error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	} else {
		//获取下一条数据
		err := tx.Where("sort>? and overwrite_type=? and domain_id =?", data.Sort, d.OverWriteType, d.DomainId).Order("sort asc").Limit(1).Find(&compareData).Error
		if err != nil {
			e.Log.Errorf("MoveView error:%s \r\n", err)
			tx.Rollback()
			return err
		}
	}
	now := time.Now().Unix()
	data.Sort, compareData.Sort = compareData.Sort, data.Sort
	err := tx.Model(&domain.OverWriteUrl{}).Where("id=?", data.Id).Updates(map[string]interface{}{"sort": data.Sort, "update_time": now}).Error
	if err != nil {
		e.Log.Errorf("MoveView error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	err = tx.Model(&domain.OverWriteUrl{}).Where("id=?", compareData.Id).Updates(map[string]interface{}{"sort": compareData.Sort, "update_time": now}).Error
	if err != nil {
		e.Log.Errorf("MoveView error:%s \r\n", err)
		tx.Rollback()
		return err
	}
	tx.Commit()
	return nil
}

func (e *DomainConfig) GetDomain(d *dto.GetByDomainReq) (domain.DomainConfig, error) {

	data := domain.DomainConfig{}
	err := e.Orm.Model(&domain.DomainConfig{}).Where("tenant_id=? and ac_domain=?", d.TenantId, d.Domain).Find(&data).Error
	if err != nil {
		e.Log.Errorf("CheckPem error:%s \r\n", err)
		return data, err
	}
	return data, err
}

func (e *DomainConfig) SaveMultiHeaderConfig(tx *gorm.DB, c *dto.MultiHeaderConfigSaveReq, isSkip bool) error {

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}

	err = tx.Model(&domain.HeaderConfig{}).Where("domain_id = ? and header_type=?", c.DomainId, c.HeaderType).Delete(&domain.HeaderConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete HeaderConfig error:%s \r\n", err)
		return err
	}

	now := time.Now().Unix()
	headers := make([]domain.HeaderConfig, 0, 5)
	for _, param := range c.Params {
		header := domain.HeaderConfig{}
		header.TenantId = param.TenantId
		header.DomainId = c.DomainId
		header.HeaderKey = param.HeaderKey
		header.HeaderValue = param.HeaderValue
		header.HeaderType = param.HeaderType
		header.OperatorType = param.OperatorType
		header.CreateTime = now
		headers = append(headers, header)
	}

	if len(headers) > 0 {
		err = tx.Save(&headers).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("save SaveMultiHeaderConfig error:%s \r\n", err)
			return err
		}
	}

	if !isSkip {
		ccEngineService := ccEngineService.CCEngineService{}
		ccEngineService.Log = e.Log
		//更新域名
		model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
		if err != nil {
			e.Log.Errorf("get DomainConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if model != nil {
			req := e.GenerateDomainReq(model)
			_, err = ccEngineService.UpdateDomain(&req)
			if err != nil {
				e.Log.Errorf("CreateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}
	return nil
}

func (e *DomainConfig) SaveMultiHeaderConfig1(tx *gorm.DB, c *dto.MultiHeaderConfigSaveReq, isSkip bool) error {

	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}

	err = tx.Model(&domain.HeaderConfig{}).Where("domain_id = ?", c.DomainId).Delete(&domain.HeaderConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete HeaderConfig error:%s \r\n", err)
		return err
	}

	now := time.Now().Unix()
	headers := make([]domain.HeaderConfig, 0, 5)
	for _, param := range c.Params {
		header := domain.HeaderConfig{}
		header.TenantId = param.TenantId
		header.DomainId = c.DomainId
		header.HeaderKey = param.HeaderKey
		header.HeaderValue = param.HeaderValue
		header.HeaderType = param.HeaderType
		header.OperatorType = param.OperatorType
		header.CreateTime = now
		headers = append(headers, header)
	}

	if len(headers) > 0 {
		err = tx.Save(&headers).Error
		if err != nil {
			tx.Rollback()
			e.Log.Errorf("save SaveMultiHeaderConfig error:%s \r\n", err)
			return err
		}
	}

	if !isSkip {
		ccEngineService := ccEngineService.CCEngineService{}
		ccEngineService.Log = e.Log
		//更新域名
		model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
		if err != nil {
			e.Log.Errorf("get DomainConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if model != nil {
			req := e.GenerateDomainReq(model)
			_, err = ccEngineService.UpdateDomain(&req)
			if err != nil {
				e.Log.Errorf("CreateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}
	return nil
}

func (e *DomainConfig) SaveCompressConfig(tx *gorm.DB, c *dto.CompressConfigSaveReq, isSkip bool) error {
	var domainConfig domain.DomainConfig
	err := tx.Model(&domain.DomainConfig{}).Where("id = ?", c.DomainId).Find(&domainConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get DomainConfig error:%s \r\n", err)
		return err
	}
	if domainConfig.Id <= 0 {
		return errors.New("加速域名不存在")
	}

	compressConfig := &domain.CompressConfig{}
	err = tx.Model(&domain.CompressConfig{}).Where("domain_id=?", c.DomainId).Find(&compressConfig).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("get CompressConfig error:%s \r\n", err)
		return err
	}

	if (compressConfig.Id <= 0 || len(compressConfig.FileType) <= 0) && len(c.FileType) <= 0 {
		c.FileType = ".js,.html,.css,.xml,.json,.shtml,.htm"
	}

	if len(c.FileType) <= 0 && len(compressConfig.FileType) > 0 {
		c.FileType = compressConfig.FileType
	}

	err = tx.Model(&domain.CompressConfig{}).Where("domain_id=?", c.DomainId).Delete(&domain.CompressConfig{}).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("delete CompressConfig error:%s \r\n", err)
		return err
	}

	fmt.Println("阿娇你说的集卡还是贷记卡回到家看哈接口的")
	now := time.Now().Unix()
	compress := &domain.CompressConfig{}
	compress.Id = c.Id
	compress.TenantId = c.TenantId
	compress.DomainId = c.DomainId
	compress.FileType = c.FileType
	compress.CompressState = c.CompressState
	compress.CompressType = c.CompressType
	compress.CreateTime = now
	compress.UpdateTime = now

	err = tx.Save(compress).Error
	if err != nil {
		tx.Rollback()
		e.Log.Errorf("Save CompressConfig error:%s \r\n", err)
		return err
	}

	if !isSkip {
		ccEngineService := ccEngineService.CCEngineService{}
		ccEngineService.Log = e.Log
		//更新域名
		model, err := e.Get(&dto.DomainConfigGetReq{Id: domainConfig.Id}, tx)
		if err != nil {
			e.Log.Errorf("get DomainConfig error:%s \r\n", err)
			tx.Rollback()
			return err
		}
		if model != nil {
			req := e.GenerateDomainReq(model)
			_, err = ccEngineService.UpdateDomain(&req)
			if err != nil {
				e.Log.Errorf("CreateDomain error:%s \r\n", err)
				tx.Rollback()
				return err
			}
		}
	}
	return nil
}

func (e *DomainConfig) GetIpInfo(c ccenginDto.GetIpInfoReq) (ccenginDto.CdnIps, error) {
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	data, err := ccEngineService.GetIpInfo(&c)
	if err != nil {
		e.Log.Errorf("GetIpInfo error:%s \r\n", err)
		return data, err
	}
	return data, err
}

var refreshHotStateMap = map[string]int{
	"processing": 1,
	"succeed":    2,
	"failed":     3,
	"waiting":    4,
	"refreshing": 5,
	"preheating": 6,
}

func (e *DomainConfig) TimeRefreshHotState() {
	ccEngineService := ccEngineService.CCEngineService{}
	ccEngineService.Log = e.Log
	taskIds := make([]string, 0, 5)
	refreshConfigs := make([]domain.RefreshConfig, 0, 5)
	refreshConfigMap := make(map[string][]domain.RefreshConfig)
	err := e.Orm.Model(&domain.RefreshConfig{}).Where("1=1").Find(&refreshConfigs).Error
	if err != nil {
		e.Log.Errorf("get RefreshConfig error:%s \r\n", err)
	}

	repeatTskIdMap := make(map[string]struct{})
	notCompleteTaskStateMap := make(map[string]struct{})
	for _, config := range refreshConfigs {
		config := config
		//_, ok := repeatTskIdMap[config.RefreshTaskId]
		//if !ok {
		//	taskIds = append(taskIds, config.RefreshTaskId)
		//	repeatTskIdMap[config.RefreshTaskId] = struct{}{}
		//}

		//url := config.Url
		//configs, ok := refreshConfigMap[url]
		//if !ok {
		//	configs = make([]domain.RefreshConfig, 0, 5)
		//}
		//configs = append(configs, config)
		//refreshConfigMap[url] = configs
		//刷新预热任务未完成的记录一下
		if config.RefreshState != 2 && config.RefreshState != 3 {
			notCompleteTaskStateMap[config.RefreshTaskId] = struct{}{}
			_, ok := repeatTskIdMap[config.RefreshTaskId]
			if !ok {
				taskIds = append(taskIds, config.RefreshTaskId)
				repeatTskIdMap[config.RefreshTaskId] = struct{}{}
			}
		}
	}

	for _, config := range refreshConfigs {
		config := config
		_, ok := notCompleteTaskStateMap[config.RefreshTaskId]
		if ok {
			url := config.Url
			configs, ok := refreshConfigMap[url]
			if !ok {
				configs = make([]domain.RefreshConfig, 0, 5)
			}
			configs = append(configs, config)
			refreshConfigMap[url] = configs
		}

	}

	for _, taskId := range taskIds {
		taskId := taskId
		_, ok := notCompleteTaskStateMap[taskId]
		if !ok {
			continue
		}
		res, err := ccEngineService.RefreshPreheat(&ccenginDto.RefreshPreheatReq{TaskId: taskId})
		if err != nil {
			e.Log.Errorf("RefreshPreheat error:%s \r\n", err)
		}
		for _, preheatRes := range *res {
			preheatRes := preheatRes
			refreshConfigs, ok := refreshConfigMap[preheatRes.Url]
			if !ok {
				return
			}
			for _, refreshConfig := range refreshConfigs {
				refreshConfig := refreshConfig
				state := refreshHotStateMap[preheatRes.Status]
				e.Log.Trace("匹配到的地址：", preheatRes.Url, refreshConfig.RefreshState, state)
				refreshConfig.RefreshState = state
				err = e.Orm.Save(&refreshConfig).Error
				if err != nil {
					e.Log.Errorf("save refreshConfig error:%s \r\n", err)
					return
				}
			}
		}
	}
}
